package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.UserCredit
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CreditViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow<CreditUiState>(CreditUiState.Loading)
    val uiState: StateFlow<CreditUiState> = _uiState

    init {
        loadUserCredit()
    }

    fun loadUserCredit() {
        viewModelScope.launch {
            _uiState.value = CreditUiState.Loading
            repository.getUserCredit()
                .catch { e ->
                    _uiState.value = CreditUiState.Error(e.message ?: "Failed to load credit data")
                }
                .collect { result ->
                    result.fold(
                        onSuccess = { credit ->
                            _uiState.value = CreditUiState.Success(credit)
                        },
                        onFailure = { error ->
                            _uiState.value = CreditUiState.Error(error.message ?: "Failed to load credit data")
                        }
                    )
                }
        }
    }


}

sealed class CreditUiState {
    object Loading : CreditUiState()
    data class Success(val credit: UserCredit) : CreditUiState()
    data class Error(val message: String) : CreditUiState()
}